Helpful Information
 
 
Category: C
C --> String Arrays

Hello, I know i am going to kick myself for asking this, but how do i access one and only one letter of a string array. For example if i have something like the following...*note i jsut made this up now so i know everything isn't there i need* when i run something like this however I can't seem to isolate each letter in the array individually. I need some way to access only the given letter of the array and nothing else. I have tried making another string of length one equal to dog[i], but that yeilds the same problem. Any help would be greatly appreciated. If you need any clarification feel free to ask. An example of what i am talking aobut is say the user enters the word dog...the following would appear...dog...og..g...I jsut want it to go d..o..g

Thank you for your time

char dog[10];
int length;

gets(dog);
length = strlen(dog);

for(i=0;i<length;i++){
printf("%s\n", &dog[i]);
}

it's just dog[i]

The problem is probably is that you're using %s with sprintf. When you give it &dog[i] it's getting a pointer to whatever index of the array its on and it will follow the pointer until it gets to the null terminator, as per the definition of a C string, so it'll print out everything from the ith character on.

If you use %c it works as expected (I also changed gets to fgets to guard against the buffer overflow):



#define MAX_DOG_LEN 10

int main(int argc, char* argv[])
{
char dog[MAX_DOG_LEN];
int length, i;

fgets(dog, MAX_DOG_LEN, stdin);
length = strlen(dog);
for (i = 0; i < length; ++i)
if (dog[i] != '\n')
printf("%c\n", dog[i]);
return 0;
}

Thank you it works beautifully










privacy (GDPR)